// 权限控制
import { getToken } from '@/utils/auth'
import router from '@/router/index'
import store from './store'

const WHITELIST = ['/login', '/404']
router.beforeEach((to, from, next) => {
  const token = getToken()
  // to and from are both route objects. must call `next`.
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      if (!store.state.user.userInfo.userId) {
        store.dispatch('user/fetchUserInfo')
      }
    }
  } else {
    if (WHITELIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
